package com.heima.audit.baidu;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import okhttp3.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;

/**
 * 百度审核类
 *
 * @Author mr.lin
 * @Date 2025/1/29 14:57
 */
@Component
@ConfigurationProperties(prefix = "baidu")
@Getter
@Setter
public class BaiduScan {

    private String apiKey;

    private String secretKey;

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    /**
     * 图片审核方法
     * @param bytes
     * @return
     */
    public Integer imageScan(byte[] bytes) {
        try {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            // image 可以通过 getFileContentAsBase64("C:\fakepath\【哲风壁纸】女明星-章若楠.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            RequestBody body = RequestBody.create(mediaType, "image=" + getFileContentAsBase64(bytes));
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            Map map = JSON.parseObject(response.body().string(), Map.class);
            System.out.println("==========图片审核结果===========");
            System.out.println(map);
            return (Integer) map.get("conclusionType");
        } catch (IOException e) {
            return 4;
        }
    }

    /**
     * 获取文件base64编码
     */
    private String getFileContentAsBase64(byte[] bytes) throws IOException {
        return URLEncoder.encode(Base64.getEncoder().encodeToString(bytes), "UTF-8");
    }


    /**
     * 文本审核方法
     * 1.合规 2.不合规 3.疑似 4.审核失败
     *
     * @param text
     * @return
     */
    public Integer textScan(String text) {
        try {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "text=" + text);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            Map map = JSON.parseObject(response.body().string(), Map.class);
            System.out.println("==========文本审核结果===========");
            System.out.println(map);
            return (Integer) map.get("conclusionType");
        } catch (IOException e) {
            return 4;
        }
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return
     * @throws IOException
     */
    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + apiKey + "&client_secret=" + secretKey + "&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String resJson = response.body().string();
        Map map = JSON.parseObject(resJson, Map.class);
        return (String) map.get("access_token");

    }
}
